package com.common.auth.controller;

import com.common.api.annontation.Authority;
import com.common.api.annontation.ServiceLog;
import com.common.api.enums.OperateEnum;
import com.common.api.exception.CommonException;
import com.common.api.model.PageModel;
import com.common.auth.api.dto.UserDto;
import com.common.auth.api.dto.UserPassUpdateDto;
import com.common.auth.api.service.UserService;
import com.common.auth.util.AuthConstant;
import com.common.tools.util.BaseBusyServiceUtil;
import com.common.web.annotation.ControllerRequest;
import com.common.web.controller.BaseController;
import com.common.web.dto.request.FuzzyPageDTO;
import com.common.web.dto.response.RestResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 用户前端控制器
 * </p>
 * @author liuchao
 */
@ServiceLog
@ControllerRequest("/user/")
@Api(tags = "系统授权-用户服务接口")
public class UserController extends BaseController {

	@Autowired
	private UserService userService;

	/**
	 * 查询所有用户信息
	 * 接口的参数searchKey，已经满足通过用户名称模糊查询
	 * @param fuzzyPageDTO
	 * @return
	 */
	@ApiOperation(value = "查询所有用户信息")
	@RequestMapping(value="queryList")
	public RestResponse queryList(@RequestBody FuzzyPageDTO fuzzyPageDTO) {
		try {
			PageModel<UserDto> page= userService.queryList(fuzzyPageDTO);
			return RestResponse.success("用户查询成功!").setData(page);
		} catch (Exception e) {
			return RestResponse.failure("用户查询失败：" + e.getMessage());
		}
	}

	/**
	 * 根据用户编码查询用户已分配的角色信息
	 * @param userCode
	 * @return
	 */
	@RequestMapping(value="queryAssignedRolesByUserCode")
	@ApiOperation(value ="根据用户编码查询用户已分配的角色")
	public RestResponse queryAssignedRolesByUserCode(@RequestBody String userCode) {
		try {
			List<String> assignedRolesByUserCode = userService.getAssignedRolesByUserCode(userCode);
			return RestResponse.success("查询用户已分配的角色成功!").setData(assignedRolesByUserCode);
		} catch (Exception e) {
			return RestResponse.failure("查询失败：" + e.getMessage());
		}
	}

	/**
	 * @param dto
	 * @return
	 */
	@RequestMapping(value="save")
	@ApiOperation(value ="保存用户信息")
	@Authority(authous = { "user/userEdit" })
	public RestResponse saveUserInfo(@RequestBody UserDto dto) {
		String operation = StringUtils.isBlank(dto.getId()) ? OperateEnum.addUser.getEnumName() : OperateEnum.updateUser.getEnumName();
		try {
			executeRoleOperation(dto, operation);
			return RestResponse.success(operation + "成功！");
		} catch (Exception e) {
			return RestResponse.failure(operation + "失败：" + e.getMessage());
		}
	}
	private void executeRoleOperation(UserDto dto, String operation) {
		if (OperateEnum.addUser.getEnumName().equals(operation)) {
			logOperateDetails(OperateEnum.addUser, getUserCode(), dto);
			userService.add(dto);
		} else if (OperateEnum.updateUser.getEnumName().equals(operation)) {
			logOperateDetails(OperateEnum.updateUser, getUserCode(), dto);
			userService.modify(dto);
		}
	}

	private void logOperateDetails(OperateEnum operateEnum, String userCode, UserDto dto) {
		BaseBusyServiceUtil.addOperateLog(operateEnum, userCode, dto);
	}


	/**
	 *
	 * 重置密码：固定密码抽取到配置文件，在操作日志表中记录相关的操作信息
	 * @param userCode
	 * @return
	 */
	@RequestMapping(value="resetPassword")
	@ApiOperation(value ="重置密码")
	@Authority(authous = { "user/resetPwd" })
	public RestResponse resetPassword(@RequestBody String userCode) {
		try {
			// 只有管理员用户才能重置自己的密码
			validateUserForPasswordReset(userCode, getUserCode());
			userService.resetPassword(userCode);
			// 记录操作日志
			String logMessage = getUserCode() + "为" + userCode + "重置密码成功";
			BaseBusyServiceUtil.addOperateLog(OperateEnum.resetPwd, userCode, logMessage);
			return RestResponse.success("重置密码成功!");
		} catch (Exception e) {
			return RestResponse.failure("重置密码失败：" + e.getMessage());
		}
	}


	/**
	 *
	 * 非管理员用户不能重置管理员的密码！
	 * @param userCode
	 * @param loginUserCode
	 */
	private void validateUserForPasswordReset(String userCode, String loginUserCode) {
		// 管理员权限检查
		if (Objects.equals(AuthConstant.ADMIN_USER, userCode) && !Objects.equals(AuthConstant.ADMIN_USER, loginUserCode)) {
			throw new CommonException("非管理员用户不能重置管理员的密码！");
		}
	}


	/**
	 *
	 * 根据主键批量删除用户
	 * @param idList
	 * @return
	 */
	@RequestMapping(value="dels")
	@ApiOperation(value ="根据主键批量删除用户")
	@Authority(authous = { "user/userEdit" })
	public RestResponse deleteUserByBatchIds(@RequestBody List<String> idList) {
		try {
			userService.dels(idList);
			String logMessage = "删除用户" + idList.toString() + "成功！";
			BaseBusyServiceUtil.addOperateLog(OperateEnum.removeUser, getUserCode(), logMessage);
			return RestResponse.success("用户删除成功！");
		} catch (Exception e) {
			return RestResponse.failure("用户删除失败："+ e.getMessage());
		}
	}


	/**
	 *   为用户分配角色
	 */
	@RequestMapping(value="assignRolesToUser")
	@ApiOperation(value ="为用户分配角色")
	@Authority(authous = { "user/assignRole" })
	public RestResponse assignRolesToUser(@RequestBody UserDto userDto) {
		try {
			// 为用户分配角色
			userService.assignRolesToUser(userDto);
			String logMessage = "为用户 " + userDto.getUserCode() + " 分配了角色：" + userDto.getUserRoleRelationPoList();
			//记录操作日志
			BaseBusyServiceUtil.addOperateLog(OperateEnum.assignRoles, getUserCode(), logMessage);
			return RestResponse.success("用户角色分配成功");
		} catch (Exception e) {
			return RestResponse.failure("为用户分配角色失败：" + e.getMessage());
		}
	}


	/**
	 *   启用和禁用用户
	 */
	@RequestMapping(value="enableFlagToUser")
	@ApiOperation(value ="用户启用/禁用")
	@Authority(authous = { "user/userEdit" })
	public RestResponse enableFlagToUser(@RequestBody String userCode) {
		try {
			userService.toggleUserEnableStatus(userCode);
			//记录操作日志
			String logMessage = "用户 " + userCode + " 启用或禁用成功！" ;
			BaseBusyServiceUtil.addOperateLog(OperateEnum.updateUser, getUserCode(), logMessage);
			return RestResponse.success("用户启用或禁用成功！");
		} catch (Exception e) {
			return RestResponse.failure("用户启用或禁用失败：" + e.getMessage());
		}
	}
}
